package com.kx.smsplatform.service.impl;

import com.kx.smsplatform.client.CacheClient;
import com.kx.smsplatform.common.constants.CacheConstants;
import com.kx.smsplatform.common.constants.RabbitMQConstants;
import com.kx.smsplatform.common.constants.SourceType;
import com.kx.smsplatform.common.enums.InterfaceExceptionEnums;
import com.kx.smsplatform.common.exception.SmsException;
import com.kx.smsplatform.common.model.StandardSubmit;
import com.kx.smsplatform.service.InterfaceService;
import com.kx.smsplatform.util.MD5Builder;
import com.kx.smsplatform.util.PhoneFormatCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class InterfaceServiceImpl implements InterfaceService {

    @Resource
    private CacheClient cacheClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void checkParameterAndSendMessage2MQ(Map map) {
        //1. 校验clientID,调用缓存模块查询客户信息,有结果,说明clienID正确.
         String clientID = map.get("clientID")+"";
        Map clientInfo = cacheClient.hGetAll(CacheConstants.CACHE_PREFIX_CLIENT+clientID);
        if (StringUtils.isEmpty(clientID)||clientInfo.size()==0) {
            log.info("【接口模块-参数校验】 clientID错误！ clientID = {}",clientID);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_CLIENT_ID_ERROR);
        }

        //2. 校验pwd,不能为null,并且要客户信息中的pwd保持一致
        String pwd =  map.get("pwd") +"";
        String pwsCache=cacheClient.hGetAll(CacheConstants.CACHE_PREFIX_CLIENT+clientID).get("pwd")+"";
        if (StringUtils.isEmpty(pwd)||!MD5Builder.build(pwd,"UTF-8").equalsIgnoreCase(pwsCache)) {
            log.info("【接口模块-参数校验】 pwd错误！ pwd = {}",pwd);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_PWD_ERROR);
        }
        //3. 校验ip,要求ip不能为null,并且匹配客户信息中的白名单地址
        String ip = map.get("ip")+"";
        String ipaddress = cacheClient.hGetAll(CacheConstants.CACHE_PREFIX_CLIENT + clientID).get("ipaddress")+"";
        String[] ipWhite = ipaddress.split(",");
        if(StringUtils.isEmpty(ip)||!Arrays.asList(ipWhite).contains(ip)){
            log.info("【接口模块-参数校验】 ipaddress错误！ ipaddress = {}",ipaddress);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_IP_ERROR);
        }
        //4. 校验content,要求不能为null,并且长度小于500
        String content =map.get("content")+"";
        if(StringUtils.isEmpty(content)||content.length()>=500){
            log.info("【接口模块-参数校验】 content错误！ content = {}",content);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_CONTENT_ERROR);
        }
        //5. 校验手机号,手机号不能为null,多个用英文逗号隔开,并且不能超过100个
        //5.1 手机号不能为空
        String mobiles = (String) map.get("mobile") ;
        if (StringUtils.isEmpty(mobiles)) {
            log.info("【接口模块-参数校验】 mobile错误,手机号不能为空！ mobiles = {}",mobiles);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        //5.2 将手机号用英文逗号隔开,判断长度不能大于100
        String[] mobileArray = mobiles.split(",");
        if(mobileArray.length>100){
            log.info("【接口模块-参数校验】 mobile错误,长度超过100个！ mobileArray = {}", Arrays.toString(mobileArray));
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        //5.3 将正确手机号收集到一个集合,错误手机号收集到一个集合
        Set<String> legalMobile = new HashSet<>();       // 正常发送短信
        Set<String> notLegalMobile = new HashSet<>();        // 发送短信完毕后,将当前不合法的手机号返回给客户端
        for (String mobile : mobileArray) {
            if(PhoneFormatCheckUtil.isChinaPhoneLegal(mobile)){
                legalMobile.add(mobile);
            }else {
                notLegalMobile.add(mobile);
            }
        }
        //6. 校验srcID, 必须是数值,并且可以转成Long
        long srcID;
        try {
           srcID = Long.parseLong(map.get("srcID")+"");
        } catch (NumberFormatException e) {
            log.info("【接口模块-参数校验】 srcID错误！ srcID = {}",e.getMessage());
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_SRC_ID_ERROR);
        }
        //7. 将正确的手机号码封装成一个指定的对象(消息)
        for (String mobile : legalMobile) {
            //7. 将正确的手机号码封装成一个指定的对象(消息)   StandardSubmit
            StandardSubmit submit = new StandardSubmit();
            submit.setClientID(Integer.valueOf(clientID +""));
            submit.setSrcSequenceId(srcID);
            submit.setDestMobile(mobile);
            submit.setMessageContent((String) map.get("content"));
            submit.setSource(SourceType.HTTP);
            //8. 以一条短信一个消息的形式,发送到MQ中.
            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND,submit);
        }

        //9. 如果有错误的手机号,返回错误手机号信息
        if(notLegalMobile.size() > 0){
            log.info("【接口模块-参数校验】  有错误手机号, notLegalMobile = {}", notLegalMobile);
            throw new SmsException(InterfaceExceptionEnums.INTERFACE_SEND_SUCCESS_AND_ERROR_MOBILE,notLegalMobile);
        }
    }

}
